package com.example.capturedemo

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.PixelFormat
import android.hardware.display.DisplayManager
import android.media.ImageReader
import android.media.projection.MediaProjectionManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.PixelCopy
import android.view.SurfaceView
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import coil.load
import com.example.capturedemo.databinding.CaptureActivityBinding
import java.nio.ByteBuffer

/**
 * @Author Xzh
 * @Date 2024/12/10
 * @Description
 */
class CaptureActivity : AppCompatActivity() {

    companion object{
        const val TAG = "CaptureActivity"
        const val REQUEST_CODE = 0x10
    }

    private val mBinding: CaptureActivityBinding by lazy {
        CaptureActivityBinding.inflate(layoutInflater)
    }
    private lateinit var   imageReader : ImageReader

    private val mMediaProjectionManager   by lazy {
//        (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE)
        getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(mBinding.root)
        initImagerReader()
        initView()
    }

    private fun initView() {
        mBinding.tvPropaganda.setText("测试测试 测试测试测试！！！！123123123")
        //截图1
        mBinding.capture.setOnClickListener {
            showImageView(decorViewCapture())
        }
        mBinding.capture2.setOnClickListener {
            pixelCopyCapture(mBinding.tvPropaganda)
//            showImageView(mBinding.tvPropaganda.bitmap)
        }
        mBinding.capture3.setOnClickListener {
            //获取权限
            val intent = mMediaProjectionManager.createScreenCaptureIntent()
            startActivityForResult(intent,REQUEST_CODE)

            startCapture()
            //创建虚拟屏
//            val virtualDisplay = VirtualDisplay

        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE){
            if (data != null) {
               val mediaProjection =  mMediaProjectionManager.getMediaProjection(resultCode, data)
                //创建虚拟屏
                mediaProjection.createVirtualDisplay("shot_image",
                    windowManager.getDefaultDisplay().getWidth(),
                    windowManager.getDefaultDisplay().getHeight(),
                    this.resources.displayMetrics.densityDpi,
                    DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                    imageReader.getSurface(), null, null);
            };
        }
    }

    /**
     * decorview截图
     */
    private fun decorViewCapture(): Bitmap {
        val rootView = window.decorView
        rootView.isDrawingCacheEnabled = true
        val bitmap = Bitmap.createBitmap(rootView.drawingCache)
        return bitmap
    }

    /**
     * PixelCopy截图
     */

    private fun pixelCopyCapture(view: SurfaceView): Bitmap {
        val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
        PixelCopy.request(view, bitmap, object : PixelCopy.OnPixelCopyFinishedListener {
            override fun onPixelCopyFinished(copyResult: Int) {
                if (copyResult == PixelCopy.SUCCESS) {
                    //截图成功
                    showImageView(bitmap)
                } else {
                    //截图失败
                    Toast.makeText(this@CaptureActivity, "截图失败", Toast.LENGTH_SHORT).show()
                }
            }
        }, Handler(Looper.getMainLooper()))
        return bitmap
    }

    /**
     * 虚拟屏截图，支持7.0以下版本
     */
    private fun initImagerReader() {
        val height = this.resources.displayMetrics.heightPixels
        val width =this.resources.displayMetrics.widthPixels
//        val format = ImageFormat.YUV_420_888
        val format = PixelFormat.RGBA_8888
        val imageMax = 1//一次捕获最大值
        //创建ImagerReader
         imageReader = ImageReader.newInstance(width, height, format, imageMax)
        //设置监听
        imageReader.setOnImageAvailableListener(object : ImageReader.OnImageAvailableListener {
            override fun onImageAvailable(reader: ImageReader?) {
//                //图像可用时操作
//                val image = imageReader.acquireLatestImage() ?: return
//                Log.e(TAG, "onImageAvailable: ${image.planes.size}")
////                val imageBuffer = image.planes[0].buffer
////                val bytes = ByteArray(imageBuffer.capacity())
////                imageBuffer.get(bytes)
////                val bitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.size,null)
////
////                showImageView(bitmap)
////                image.close()
//
//                val width = image.width
//                val height = image.height
//                val planes = image.planes
//                val buffer: ByteBuffer = planes[0].getBuffer()
//                val pixelStride: Int = planes[0].getPixelStride()
//                val rowStride: Int = planes[0].getRowStride()
//                val rowPadding = rowStride - pixelStride * width
//                var bitmap = Bitmap.createBitmap(
//                    width + rowPadding / pixelStride,
//                    height,
//                    Bitmap.Config.ARGB_8888
//                )
//                bitmap.copyPixelsFromBuffer(buffer)
//                bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height)
//                showImageView(bitmap)
//                image.close()
            }

        }, Handler(Looper.getMainLooper()))
    }

    private fun  startCapture(){
        //图像可用时操作
        val image = imageReader.acquireLatestImage() ?: return
        Log.e(TAG, "onImageAvailable: ${image.planes.size}")
//                val imageBuffer = image.planes[0].buffer
//                val bytes = ByteArray(imageBuffer.capacity())
//                imageBuffer.get(bytes)
//                val bitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.size,null)
//
//                showImageView(bitmap)
//                image.close()

        val width = image.width
        val height = image.height
        val planes = image.planes
        val buffer: ByteBuffer = planes[0].getBuffer()
        val pixelStride: Int = planes[0].getPixelStride()
        val rowStride: Int = planes[0].getRowStride()
        val rowPadding = rowStride - pixelStride * width
        var bitmap = Bitmap.createBitmap(
            width + rowPadding / pixelStride,
            height,
            Bitmap.Config.ARGB_8888
        )
        bitmap.copyPixelsFromBuffer(buffer)
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height)
        showImageView(bitmap)
        image.close()
    }

    /**
     * 展示图片
     */
    private fun showImageView(bitmap: Bitmap) {
        mBinding.image.load(bitmap)
        mBinding.imageContainer.visibility = View.VISIBLE
        mBinding.otherContainer.visibility = View.GONE
        mBinding.tvPropaganda.visibility = View.GONE
    }


    override fun onBackPressed() {
        if (mBinding.imageContainer.visibility == View.VISIBLE) {
            mBinding.imageContainer.visibility = View.GONE
            mBinding.otherContainer.visibility = View.VISIBLE
            mBinding.tvPropaganda.visibility = View.VISIBLE
        } else {
            super.onBackPressed()
        }

    }
}